package server

import (
	"net"
	"net/http"
	"sieve_admin_server_userpass/lib/app"
	"sieve_admin_server_userpass/lib/config"
	"sieve_admin_server_userpass/lib/mysql"
	"strings"
	"time"
)

var (
	fDBAddr = config.String("db.mysql.addr", "127.0.0.1:3306", "mysql addr")
	fDBName = config.String("db.mysql.name", "", "mysql db name")
	fDBUser = config.String("db.mysql.user", "", "mysql db user")
	fDBPwd  = config.String("db.mysql.pwd", "", "mysql db password")

	fSuperDBAddr = config.String("db.super.addr", "127.0.0.1:3306", "mysql addr")
	fSuperDBName = config.String("db.super.name", "", "mysql db name")
	fSuperDBUser = config.String("db.super.user", "", "mysql db user")
	fSuperDBPwd  = config.String("db.super.pwd", "", "mysql db password")

	dbInits = []func(){}
	db      *mysql.DB
	superdb *mysql.DB
)

func init() {
	app.OnStart(func() {
		db, _ = mysql.Open(*fDBAddr, *fDBUser, *fDBPwd, *fDBName)
		superdb, _ = mysql.Open(*fSuperDBAddr, *fSuperDBUser, *fSuperDBPwd, *fSuperDBName)

		db.Exec("CREATE TABLE IF NOT EXISTS `app_user` ( `Uid` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(64) COLLATE utf8mb4_bin NOT NULL, `roleName` varchar(64) COLLATE utf8mb4_bin NOT NULL,`Leader` int(10) NOT NULL, PRIMARY KEY (`Uid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")
		db.Exec("CREATE TABLE IF NOT EXISTS `app_role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Name` varchar(255) COLLATE utf8mb4_bin NOT NULL, `Perms` text COLLATE utf8mb4_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")
		db.Exec("CREATE TABLE IF NOT EXISTS `app_session` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Uid` bigint(20) NOT NULL, `SessionKey` varchar(32) COLLATE utf8mb4_bin NOT NULL, `ExpireTime` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")
		db.Exec("CREATE TABLE IF NOT EXISTS `app_op_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Uid` bigint(20) NOT NULL, `Path` varchar(255) COLLATE utf8mb4_bin NOT NULL, `Params` text COLLATE utf8mb4_bin NOT NULL, `IP` varchar(16) COLLATE utf8mb4_bin NOT NULL, `UA` text COLLATE utf8mb4_bin NOT NULL, `CreateTime` int(11) NOT NULL, `ExecTime` varchar(16) COLLATE utf8mb4_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;")

		for _, fn := range dbInits {
			fn()
		}
	})
}

func AfterDbOpen(fn func()) {
	dbInits = append(dbInits, fn)
}

func DB() *mysql.DB      { return db }
func SuperDB() *mysql.DB { return superdb }

func addOpLog(uid int, r *http.Request, t time.Time) {
	db.Exec("INSERT INTO app_op_log (Uid,Path,Params,IP,UA,CreateTime,ExecTime) VALUES (?,?,?,?,?,?,?)", uid, r.URL.Path, r.Form.Encode(), remoteIP(r), r.UserAgent(), t.Unix(), time.Now().Sub(t).String())
}

func remoteIP(r *http.Request) string {
	if s := r.Header.Get("X-Forwarded-For"); s != "" {
		ss := strings.Split(s, ", ")
		return ss[0]
	}
	ip, _, _ := net.SplitHostPort(r.RemoteAddr)
	return ip
}
